package city.spring.modules.material.controller;

import city.spring.modules.material.dto.StorehouseDTO;
import city.spring.modules.material.entity.StorehouseEntity;
import city.spring.modules.material.service.StorehouseService;
import city.spring.modules.material.vo.StorehouseVO;
import city.spring.modules.personnel.service.EmployeeService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/storehouse")
public class StorehouseController extends ApiController {
    /**
     * <strong>仓库设置</strong> Service
     */
    private final StorehouseService storehouseService;
    private final EmployeeService employeeService;
    /**
     * 实体类（仓库设置）可排序字段
     */
    private final List<SFunction<StorehouseEntity, ?>> entityOrderFields;

    public StorehouseController(StorehouseService storehouseService, EmployeeService employeeService) {
        this.storehouseService = storehouseService;
        this.employeeService = employeeService;
        this.entityOrderFields = new ArrayList<>();
        entityOrderFields.add(StorehouseEntity::getId);
        entityOrderFields.add(StorehouseEntity::getSname);
        entityOrderFields.add(StorehouseEntity::getAddress);
        entityOrderFields.add(StorehouseEntity::getUserId);
        entityOrderFields.add(StorehouseEntity::getGmtCreate);
        entityOrderFields.add(StorehouseEntity::getGmtModified);
    }

//    /**
//     * 获取全部的 <strong>仓库设置</strong> 列表
//     */
//    @GetMapping("all")
//    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, StorehouseEntity entity) {
//        LambdaQueryChainWrapper<StorehouseEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        List<StorehouseEntity> list = lambdaQuery.list();
//        return success(list);
//
//    }

    /**
     * 分页获取 <strong>仓库设置</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault(sort = {"sname"}) Pageable pageable, StorehouseVO entity) {

        QueryWrapper<? extends StorehouseEntity> queryWrapper = buildQuery(entity);
        return success(storehouseService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<StorehouseEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<StorehouseEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (StorehouseEntity record : page.getRecords()) {
//            try {
//                EmployeeEntity employeeEntity = employeeService.getById(record.getUserId());
//                record.setName(employeeEntity.getName());
//            } catch (Exception ignore) {
//                record.setUserId(null);
//                record.setName("< 找不到管理员 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 获取一个 <strong>仓库设置</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

        QueryWrapper<StorehouseVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<StorehouseVO> records = storehouseService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(storehouseService.getById(id));
    }

    /**
     * 添加一个 <strong>仓库设置</strong>
     *
     * @param entity 新增的信息
     */
    @PostMapping
    public Object add(@RequestBody StorehouseDTO entity) {
        storehouseService.saveStorehouse(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }


    /**
     * 修改一个 <strong>仓库设置</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody StorehouseEntity entity) {
//        storehouseService.lambdaUpdate()
//                .set(StorehouseEntity::getId, entity.getId())
//                .set(StorehouseEntity::getSname, entity.getSname())
//                .set(StorehouseEntity::getAddress, entity.getAddress())
//                .set(StorehouseEntity::getUserId, entity.getUserId())
//                .set(StorehouseEntity::getDescription, entity.getDescription())
//                .set(StorehouseEntity::getStype, entity.getStype())
//                .eq(StorehouseEntity::getId, id)
//                .update();
//        return new ResponseEntity<>(HttpStatus.OK);
        entity.setId(id);
        storehouseService.updateStorehouse(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>仓库设置</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        storehouseService.deleteStorehouse(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>仓库设置</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        storehouseService.deleteStorehouse(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong>仓库设置</strong>
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<StorehouseEntity> buildLambdaQuery(StorehouseEntity entity) {
        LambdaQueryChainWrapper<StorehouseEntity> lambdaQuery = storehouseService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, StorehouseEntity::getId, entity.getId());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getSname()), StorehouseEntity::getSname, entity.getSname());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getAddress()), StorehouseEntity::getAddress, entity.getAddress());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<StorehouseEntity> buildQuery(StorehouseVO entity) {
        QueryWrapper<StorehouseEntity> wrapper = new QueryWrapper<>();
        wrapper.like(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(entity.getUserId() != null, "t1.user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t2.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getSname()), "t1.sname", entity.getSname());
//        wrapper.like(entity.getApplicationdate() != null, "t3.applicationdate", entity.getApplicationdate());
        return wrapper;
    }

    /**
     * 获取正在使用的仓库 列表展示
     *
     * @return
     */
    @GetMapping("/all")
    public Object getStorehouseAll() {
        return success(storehouseService.getStorehouseAll());
    }
}
